const http = require('http');

//通过http对象创建一个服务器
const server = http.createServer((req, res) => {
    //接收客户端发过来的get请求
    let queryString = decodeURI(req.url)  //这里返回的是/?name=tom 和/?username=mary&userage=20
    let reqValueArr = getValueMutil(queryString)
    // let reqValueArr1 = getValue(queryString)
    console.log(reqValueArr)

    // let name = "李四"
    // console.log(name)
    // let newUrl = encodeURI(`http://www.baidu.com/s?search=${name}&key=hello world`)
    // console.log(newUrl)
    // console.log(decodeURI(newUrl))  //这里要使用decodeURI才会是用中文的，不然会用其他的方式编码
    if(reqValueArr){
        res.writeHead(200, { 'Content-Type': 'text/plain;charset=utf-8' });
        res.write('tom的基本信息\n');  //向响应对象书写字符串
        res.write(`name:${reqValueArr[0]}\n`);
        res.write(`age:${reqValueArr[1]}\n`);
        res.end(reqValueArr.join('\n'));  //向响应告知，输入完毕
    }
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});

function getValue(queryString)
{
    //获取值
    let queryArr = queryString.substring('?')  //name=tom
    return queryArr.substring(queryArr.indexOf('=')+1)  //tom ,我这里的=号是首个的=号，使用lastIndexOf更妥当
}

function getValueMutil(queryString)
{
    if(queryString !== "/favicon.ico"){
        //获取值
        let queryArr = queryString.substring('?')  //name=tom
        let queryArr1 = queryArr.split('&')  //['name=tom','username=mary','userage=20']

        console.log(queryArr1)
        let returnVal = queryArr1.map(item => {
            return item.substring(item.lastIndexOf('=')+1)
        })
        return returnVal
    }
}